//
//  ViewFileListController.m
//  aestest
//
//  Created by yaoziyang on 14-7-10.
//  Copyright (c) 2014年 yaoziyang. All rights reserved.
//

#import "ViewFileListController.h"
#import "OpenFileNavigationController.h"
#import <openssl/aes.h>
#import <CommonCrypto/CommonCryptor.h>
#import "stdio.h"

enum
{
    DEFAULT_FILE_SECTION = 0,
    MAX_FILE_SECTIONS = 1
};

@interface ViewFileListController ()
{
    UITableView* filelistView;
    NSArray* encryptFileItems;
}
@end

@implementation ViewFileListController
@synthesize targetFolder;

- (id)initWithTargetFolder:(NSURL*)folder
{
    if (self = [self initWithNibName:nil bundle:nil]) {
        self.targetFolder = folder;
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"选择加密文件";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSError* fmError = nil;
    NSFileManager* fm = [[NSFileManager alloc]init];
    NSDirectoryEnumerationOptions options = NSDirectoryEnumerationSkipsHiddenFiles | NSDirectoryEnumerationSkipsPackageDescendants;
    encryptFileItems = [fm contentsOfDirectoryAtURL:targetFolder
              includingPropertiesForKeys:[NSArray arrayWithObject:NSURLIsRegularFileKey]
                                 options:options
                                   error:&fmError];
    
    encryptFileItems = [encryptFileItems sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSURL* path1 = obj1;
        NSURL* path2 = obj2;
        BOOL path1IsDir = [self isDirectory:path1];
        BOOL path2IsDir = [self isDirectory:path2];
        if (path1IsDir && path2IsDir) {
            return [path1.path compare:path2.path options:NSCaseInsensitiveSearch];
        }
        else if(!path1IsDir && !path2IsDir)
            return [path1.path compare:path2.path options:NSCaseInsensitiveSearch];
        else if(path1IsDir)
            return NSOrderedAscending;
        else
            return NSOrderedDescending;
    }];
    
    if (fmError) {
        NSLog(@"%@", fmError);
    }
    
    filelistView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    filelistView.dataSource = self;
    filelistView.delegate = self;
    [self.view addSubview:filelistView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)isDirectory:(NSURL*)url
{
    NSNumber* isDir = 0;
    [url getResourceValue:&isDir forKey:NSURLIsDirectoryKey error:nil];
    if (isDir && [isDir boolValue])
        return [isDir boolValue];
    return NO;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return MAX_FILE_SECTIONS;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == DEFAULT_FILE_SECTION) {
        return encryptFileItems.count;
    }else
        return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString* sid = [NSString stringWithFormat:@"%d-%d", indexPath.section, indexPath.row];
    UITableViewCell* cell = [filelistView dequeueReusableCellWithIdentifier:sid];
    if(cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:sid];
    }
    
    if (indexPath.section == DEFAULT_FILE_SECTION && indexPath.row < encryptFileItems.count) {
        NSURL* fileURL = (NSURL*)[encryptFileItems objectAtIndex:indexPath.row];
        cell.textLabel.text = [fileURL lastPathComponent];
        if ([self isDirectory:fileURL])
            cell.image = [UIImage imageNamed:@"dir.png"];
        else
            cell.image = [UIImage imageNamed:@"file.png"];
        return cell;
    }else
        return nil;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == DEFAULT_FILE_SECTION) {
        return [NSString stringWithFormat:@"位于%@下", [self.targetFolder lastPathComponent]];
    }else
        return nil;
}

- (long long) fileSizeAtPath:(NSString*) filePath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == DEFAULT_FILE_SECTION && indexPath.row < encryptFileItems.count) {
        
        /*NSURL* fileURL = (NSURL*)[encryptFileItems objectAtIndex:indexPath.row];
        FILE* fp = fopen([fileURL.path cStringUsingEncoding:NSUTF8StringEncoding], "r");
        if(!fp) {
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil message:@"打不开文件" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            return;
        }
        
        int filesize = (int)[self fileSizeAtPath:fileURL.path];
        if (filesize <= 0) {
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil message:@"无效文件" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            return;
        }
        
        int bufsize = filesize + (filesize%16);
        char* buf = (char*)malloc(bufsize);
        memset(buf, 0, bufsize);
        
        if(!buf)
            return;
        
        if (!fread(buf, filesize, 1, fp)) {
            
            free(buf);
            
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil message:@"无法读取文件" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            return;
        }*/
        
        NSURL* fileURL = (NSURL*)[encryptFileItems objectAtIndex:indexPath.row];
        
        if ([self isDirectory:fileURL]) {
            ViewFileListController* fsController = [[ViewFileListController alloc] initWithTargetFolder:fileURL];
            [self.navigationController pushViewController:fsController animated:YES];
        }else {
            OpenFileNavigationController* naviController = (OpenFileNavigationController*)self.navigationController;
            naviController.goURL = fileURL;
            [naviController popToRootViewControllerAnimated:YES];
        }
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
